package me.dongcha.reggie402.controller;

import lombok.extern.slf4j.Slf4j;
import me.dongcha.reggie402.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int lastIndex = originalFilename.lastIndexOf(".");
        String fileStuff = originalFilename.substring(lastIndex);
        String fileName = UUID.randomUUID().toString() + fileStuff;

        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File destFile = new File(basePath, fileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传时遇到问题,请稍后再试");
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        log.warn("[正在下载文件]:{}", name);
        try {
            File srcFile = new File(basePath, name);
            FileInputStream in = new FileInputStream(srcFile);
            ServletOutputStream out = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[8 * 1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
